package com.levi.utils;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

/**
 * Created by Levi on 2018/4/17.
 */

public class PermissionChecker {

    public static boolean requestPermission(@NonNull Activity activity,
                                            int requestCode,
                                            @NonNull String... permissions) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || permissions.length == 0) {
            return true;
        }
        ArrayList<String> applyList = new ArrayList<>();
        for (String permission : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                    activity,
                    permission)) {
                applyList.add(permission);
            }
        }
        if (applyList.isEmpty()) {
            return true;
        }
        String[] array = new String[applyList.size()];
        ActivityCompat.requestPermissions(activity, applyList.toArray(array), requestCode);
        return false;
    }

    public static boolean checkPermission(@NonNull Context context, @NonNull String... permissions) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || permissions.length == 0) {
            return true;
        }
        ArrayList<String> applyList = new ArrayList<>();
        for (String permission : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                    context,
                    permission)) {
                applyList.add(permission);
            }
        }
        return applyList.isEmpty();
    }
}
